const nodeEnv = process.env.NODE_ENV;
const config = require('./config')[nodeEnv].dataBase;
const Sequelize = require('sequelize');
const debug = require('debug');
const model_def = require('../models');
debug(`database configuration, dbname[${config.dbname}],user[${config.user}],password[${config.password}], \
host[${config.host}],port[${config.port}]`);
const sequelize = new Sequelize(config.dbname, config.user, config.password, {
    host: config.host,
    port: config.port,
    dialect: 'mysql',
    poll: {
        max: 5,
        min: 0,
        idle: 10000
    },
    define: {
        timestamps: false
    },
    dialectOptions: {
        dateStrings: true,
        typeCast: true
    },
    timezone: '+08:00'
});

sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

let models = {};
for (let fname in model_def) {
    let model = model_def[fname](sequelize);
    debug(`model created [${model.name}]`);
    models[model.name] = model;
}

// 创建表关联
let tableRelation = [
    {
        src: 'comment_model',
        target: 'users_model',
        relation: 'belongsTo',
        options: {
            as: 'userInfo',
            foreignKey: 'from_userid',
            targetKey: 'users_id'
        }
    },
    {
        src: 'comment_model',
        target: 'reply_model',
        relation: 'hasMany',
        options: {
            as: 'reply',
            foreignKey: 'comment_id'
        }
    },
    {
        src: 'reply_model',
        target: 'users_model',
        relation: 'belongsTo',
        options: {
            as: 'userInfo',
            foreignKey: 'form_uid',
            targetKey: 'users_id'
        }
    },
    {
        src: 'reply_model',
        target: 'users_model',
        relation: 'belongsTo',
        options: {
            as: 'toUserInfo',
            foreignKey: 'to_uid',
            targetKey: 'users_id'
        }
    },
    {
        src: 'collect_model',
        target: 'sentence_model',
        relation: 'belongsTo',
        options: {
            as: 'sentence',
            foreignKey: 'sentence_id',
            targetKey: 'id'
        }
    },
    {
        src: 'zan_model',
        target: 'sentence_model',
        relation: 'belongsTo',
        options: {
            as: 'sentence',
            foreignKey: 'type_id',
            targetKey: 'id'
        }
    },
    {
        src: 'sentence_model',
        target: 'special_model',
        relation: 'belongsTo',
        options: {
            as: 'special',
            foreignKey: 'fromid',
            targetKey: 'sid'
        }
    }
]
for (let rel of tableRelation) {
    let model = models[rel.src];
    let target = models[rel.target];
    model[rel.relation](target, rel.options);
}

module.exports = { 
    models, sequelize, Sequelize
};
